import { isIOS } from './check'
import { resetWindowPosition } from './common';



export class Adaptation {
    private keyboardUpFunc?: EventListenerOrEventListenerObject
    private keyboardDownFunc?: EventListenerOrEventListenerObject

    private isKeyboardUp?: boolean;
    private timer?: NodeJS.Timeout;

    static hasAddKeyboardEvent?: boolean;

    constructor() {
        if (Adaptation.hasAddKeyboardEvent) {
            return
        }

        Adaptation.hasAddKeyboardEvent = true
        const KeyboardUpEvent = new KeyboardEvent('KeyboardUp', { bubbles: true, cancelable: true })
        const KeyboardDownEvent = new KeyboardEvent('KeyboardDown', { bubbles: true, cancelable: true })

        if (isIOS()) {
            document.body.addEventListener('focusin', () => {
                document.dispatchEvent(KeyboardUpEvent);
            })
            document.body.addEventListener('focusout', () => {
                document.dispatchEvent(KeyboardDownEvent);
            })
            return
        }

        // Android need not to Adaptation
        // const originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
        // window.onresize = function () {
        //     const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //     if (resizeHeight - 0 < originalHeight - 0) {
        //         document.dispatchEvent(KeyboardUpEvent);
        //     } else {
        //         document.dispatchEvent(KeyboardDownEvent);
        //     }
        // }
    }

    addKeyBoardEventListener = () => {
        this.keyboardUpFunc = () => {
            this.isKeyboardUp = true
        }

        this.keyboardDownFunc = () => {
            this.isKeyboardUp = false
            this.timer = setTimeout(() => {
                if (this.isKeyboardUp) {
                    clearTimeout(this.timer)
                    this.timer = undefined
                    return
                }
                if (isIOS()) {
                    // when keybord hidden, reset window poition
                    resetWindowPosition(true)
                }
            }, 100);

        }

        window.addEventListener('KeyboardUp', this.keyboardUpFunc)
        window.addEventListener('KeyboardDown', this.keyboardDownFunc)
    }

    removeKeyBoardEventListener = () => {
        this.keyboardUpFunc && window.removeEventListener('KeyboardUp', this.keyboardUpFunc)
        this.keyboardUpFunc = undefined
        this.keyboardDownFunc && window.removeEventListener('KeyboardDown', this.keyboardDownFunc)
        this.keyboardDownFunc = undefined
        clearTimeout(this.timer)
        this.timer = undefined
    }
}

